<!-- 项目评估 -->
<template>
  <div class="app-container">
    <Edialog
      :outershow="outershow"
      :title="title"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="finishFirst ? true : false"
      width="50%"
    >
      <el-row v-if="finishFirst" :gutter="20">
        <el-row :gutter="20">
          <el-form
            :rules="rules"
            :model="setOf"
            ref="setOf"
            label-width="100px"
          >
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="开始年份" prop="startTime">
                  <span>{{ setOf.startTime }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-row>
        <el-col :span="24">
          <SpreadSheet
            style="height: 55vh; width: 100%"
            ref="Sheet"
            SheetName="Sheet1"
            :File="file"
            :Headers="headers"
            :ColumnWidth="200"
            :Records="records"
            @loaded="loaded"
            @cell-selected="cellSelected"
            @cells-selected="cellsSelected"
            :onlyRead="false"
          ></SpreadSheet>
        </el-col>
      </el-row>
      <el-row v-else :gutter="20">
        <el-form
          :rules="TimeRules"
          :model="timeObj"
          ref="timeRef"
          label-width="100px"
        >
          <el-form-item label="开始年份" prop="startTime">
            <el-date-picker
              v-model="timeObj.startTime"
              type="year"
              value-format="yyyy"
              placeholder="开始年份"
            >
            </el-date-picker
          ></el-form-item>

          <el-form-item label="结束年份" prop="endTime">
            <el-date-picker
              v-model="timeObj.endTime"
              type="year"
              value-format="yyyy"
              placeholder="结束年份"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button @click="nextStepFn" type="primary">下 一 步</el-button>
            <el-button @click="outershow = false">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </Edialog>
    <subject_choose
      v-if="isShowDialog"
      @close="closeDialog"
      @successFn="successFn"
      ref="subject_choose"
    ></subject_choose>
  </div>
</template>

<script>
import { indexToCoord, getNonEmptyMergedCells } from "@/utils/spreadsheet.js";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import Edialog from "@/components/Edialog";
import subject_choose from "@/components/Xspreadsheet/subject_choose.vue";
import { ProjectEvalInfoDynamicsTemplateApi } from "@/api/projectManage";
export default {
  data() {
    return {
      //先完成第一个日期弹窗的填写
      finishFirst: false,
      setOf: {
        startTime: "",
      },
      rules: {
        code: [
          { required: true, message: "开始年份不能为空", trigger: "blur" },
        ],
      },
      timeObj: {
        code: "",
        name: "",
      },
      TimeRules: {
        startTime: [
          { required: true, message: "开始年份不能为空", trigger: "blur" },
        ],
        endTime: {
          required: true,
          message: "结束年份不能为空",
          trigger: "blur",
        },
      },

      isShowDialog: false,
      tableData: [],
      tableLoading: false,
      tableHeight: "calc(60vh - 186px)",
      //表格字段
      tableColumns: [
        {
          prop: "PARAM_VALUE1",
          label: "科目标识",
          width: "80",
        },
        {
          prop: "PARAM_VALUE2",
          label: "科目行名称",
          width: "100",
        },
        { prop: "PARAM_VALUE3", label: "科目列名称", width: "100" },
        { prop: "PARAM_VALUE4", label: "科目类型", width: "80" },
        { prop: "PARAM_VALUE5", label: "数据类型", width: "80" },
        { prop: "PARAM_VALUE6", label: "权限类型", width: "80" },
      ],
      file: null,
      ColumnCount: 30,
      RowCount: 100,
      headers: [],
      records: [],
      templateType: [
        {
          value: "1",
          label: "类型1",
        },
        {
          value: "2",
          label: "类型2",
        },
      ],
      outershow: false,
      title: "项目评估",
      form: {
        col: "",
        row: "",
        address: "",
        sAddress: "",
        eAddress: "",
      },
      selectionData: [],
      spreadsheetData: [],
      openData: {},
    };
  },
  components: {
    Edialog,
    SpreadSheet,
    subject_choose,
  },
  methods: {
    nextStepFn() {
      this.$refs.timeRef.validate(async (valid) => {
        if (valid) {
          this.finishFirst = true;
          console.log("this.timeObj", this.timeObj);
          let params = {
            startTime: this.timeObj.startTime,
            endTime: this.timeObj.endTime,
            projectCode: this.openData.projectCode,
          };
          let res = await ProjectEvalInfoDynamicsTemplateApi(params);
          if (res.data && res.data.bcode == 0) {
            console.log("res", res);
            this.dynamicsTemplateData = res.data.badata;
          }
          this.$nextTick(() => {
            //调用接口获取到spreadsheetData
            let spreadsheetData = [];
            this.spreadsheetData = spreadsheetData || [];
            setTimeout(() => {
              this.$refs.Sheet.loadData(spreadsheetData || []);
            });
          });
        }
      });
    },
    successFn(e) {
      console.log("选择成功", e);
    },
    closeDialog() {
      this.isShowDialog = false;
    },
    templatechooseFn() {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs.subject_choose.manufacturerOpen();
      });
    },
    /**
     * 获取选区非空单元格（合并单元格视为单个条目）
     * @param {Object} rows - 原始表格数据 {行索引:{cells:{列索引:单元格数据}}}
     * @param {Object} range - 选区范围 {sri:起始行,sci:起始列,eri:结束行,eci:结束列}
     * @returns {Array} 过滤后的扁平化单元格数组
     */
    getNonEmptyMergedCells(rows, range) {
      const result = [];
      const processed = new Set();

      const isEmpty = (val) => val === null || val === undefined || val === "";

      for (let r = range.sri; r <= range.eri; r++) {
        if (!rows[r]?.cells) continue;

        for (let c = range.sci; c <= range.eci; c++) {
          const cellKey = `${r},${c}`;
          if (processed.has(cellKey)) continue;

          const cell = rows[r].cells[c];
          if (!cell || isEmpty(cell.text)) continue;

          // 处理合并单元格
          if (cell.merge) {
            const [rowSpan, colSpan] = cell.merge;
            for (let i = 0; i <= rowSpan; i++) {
              for (let j = 0; j <= colSpan; j++) {
                processed.add(`${r + i},${c + j}`);
              }
            }
          }
          result.push({
            row: r,
            col: c,
            value: cell.text,
            merge: cell.merge || null,
            style: cell.style || null,
            formula: cell.formula || null,
            sharedFormula: cell.sharedFormula || null,
          });
        }
      }
      return result;
    },

    // 把坐标转为单元格引用如（A1）
    indexToCoord(rowIndex, colIndex) {
      const colLetter = String.fromCharCode(65 + colIndex);
      return `${colLetter}${rowIndex + 1}`;
    },
    cellsSelected(cell, { sri, sci, eri, eci }) {
      this.selectionData = [];
      if (cell && cell._address) {
        this.form.address = cell._address;
        this.form.sAddress = indexToCoord(sri, sci);
        this.form.eAddress = indexToCoord(eri, eci);
        this.form.text = cell.text;
      }
      const rangeData = xs.sheet.data.getData().rows;
      this.selectionData = getNonEmptyMergedCells(rangeData, {
        sri,
        sci,
        eri,
        eci,
      });
    },
    cellSelected(cell, ri, ci) {
      this.selectionData = [];
      console.log("cellSelected", cell, ri, ci);
      this.form.sAddress = "";
      this.form.eAddress = "";
      this.form.address = indexToCoord(ri, ci);
      if (cell && cell._address) {
        this.form.address = cell._address;
        this.form.text = cell.text;
      }

      this.selectionData = [cell];
    },
    addItem() {
      this.tableData = this.tableData.concat(this.selectionData);
      // 给表单数据添加表单中设置的数据属性
      this.tableData.forEach((item) => {
        item.PARAM_VALUE1 = this.form.text;
        item.PARAM_VALUE2 = this.form.templateType;
        item.PARAM_VALUE3 = this.form.dataType;
      });
    },
    deleteItem(index) {
      this.tableData.splice(index, 1);
    },
    //表格数据加载事件
    loaded(spreadsheet) {
      console.log("loaded", spreadsheet);
    },
    //外部打开弹窗
    openFn(data) {
      this.openData = data;
      console.log("open", data);

      this.finishFirst = false;
      this.outershow = true;
    },
    saveFn() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.$route.query.id) {
            editTemplate(this.form).then((res) => {
              if (res.code === 200) {
                this.$message.success("修改成功");
              }
            });
          } else {
            addTemplate(this.form).then((res) => {
              if (res.code === 200) {
                this.$message.success("新增成功");
              }
            });
          }
        }
      });
    },
    closeFn() {
      this.outershow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.el-form-item {
  width: 45%;
  // display: flex;
}
::v-deep .el-form-item__content {
  width: 60% !important;
}
.ellipsis_text {
  width: 200px; /* 或者你希望的固定宽度 */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出容器的文本 */
  text-overflow: ellipsis; /* 使用省略号表示超出容器的文本 */
}
</style>
